#!/bin/bash
# 清理并重启所有服务

echo "=========================================="
echo "   清理并重启 CMDB 服务"
echo "=========================================="
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 获取脚本目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo -e "${YELLOW}🧹 清理旧进程...${NC}"

# 强制杀掉所有相关进程
pkill -9 -f "daphne.*backend.asgi" 2>/dev/null
pkill -9 -f "vite" 2>/dev/null
pkill -9 -f "npm run dev" 2>/dev/null

sleep 2
echo -e "${GREEN}✓ 进程已清理${NC}"
echo ""

# 检查端口
echo -e "${YELLOW}🔍 检查端口占用...${NC}"
PORT_8000=$(lsof -i :8000 2>/dev/null | grep LISTEN)
PORT_8080=$(lsof -i :8080 2>/dev/null | grep LISTEN)

if [ -n "$PORT_8000" ]; then
    echo -e "${RED}⚠️  端口 8000 仍被占用${NC}"
    lsof -i :8000
    exit 1
fi

if [ -n "$PORT_8080" ]; then
    echo -e "${RED}⚠️  端口 8080 仍被占用${NC}"
    lsof -i :8080
    exit 1
fi

echo -e "${GREEN}✓ 端口 8000 和 8080 已释放${NC}"
echo ""

# 清理日志目录
mkdir -p logs
rm -f logs/backend.log logs/frontend.log 2>/dev/null
touch logs/backend.log logs/frontend.log

# 激活虚拟环境
if [ ! -d ".venv" ]; then
    echo -e "${RED}✗ 虚拟环境不存在${NC}"
    exit 1
fi

. .venv/bin/activate

# 启动后端
echo -e "${YELLOW}🚀 启动后端服务...${NC}"
cd backend
nohup daphne -b 0.0.0.0 -p 8000 backend.asgi:application > ../logs/backend.log 2>&1 &
BACKEND_PID=$!
echo $BACKEND_PID > ../logs/backend.pid
cd ..

# 等待后端启动
sleep 3
if ps -p $BACKEND_PID > /dev/null; then
    echo -e "${GREEN}✓ 后端已启动 (PID: $BACKEND_PID)${NC}"
else
    echo -e "${RED}✗ 后端启动失败${NC}"
    exit 1
fi

# 启动前端
echo -e "${YELLOW}🚀 启动前端服务...${NC}"
cd frontend
nohup npm run dev > ../logs/frontend.log 2>&1 &
sleep 2
cd ..

# 获取前端实际PID
sleep 5
FRONTEND_PID=$(ps aux | grep vite | grep -v grep | awk '{print $2}' | head -1)
if [ -n "$FRONTEND_PID" ]; then
    echo $FRONTEND_PID > logs/frontend.pid
    echo -e "${GREEN}✓ 前端已启动 (PID: $FRONTEND_PID)${NC}"
else
    echo -e "${RED}✗ 前端启动失败${NC}"
    exit 1
fi

echo ""
echo "=========================================="
echo -e "${GREEN}   ✅ 所有服务已启动${NC}"
echo "=========================================="
echo ""
echo "📊 服务信息:"
echo "  前端: http://localhost:8080 (PID: $FRONTEND_PID)"
echo "  后端: http://localhost:8000 (PID: $BACKEND_PID)"
echo ""
echo "🔍 验证服务:"
echo "  bash status.sh"
echo ""
echo "📝 查看日志:"
echo "  bash logs.sh follow"
echo ""
